package luj.tool.jnproxyan.framework.lujcluster;

import io.vertx.core.Vertx;
import luj.cluster.api.node.NodeStartListener;
import luj.net.api.NetContext;
import luj.tool.jnproxyan.framework.proxy.actor.tell.ActorTeller;
import luj.tool.jnproxyan.framework.vertx.MainVerticle;
import luj.tool.jnproxyan.proxy.admin.AdminHttpMeta;
import luj.tool.jnproxyan.proxy.network.socks.actor.root.Socks5ActorFactory;
import luj.tool.jnproxyan.proxy.network.socksv2.NettySocksStarter;
import luj.tool.jnproxyan.proxy.start.collect.HttpHandleCollector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
final class OnLujclusterStart implements NodeStartListener {

  /**
   * @see luj.tool.jnproxyan.framework.lujnet.connect.OnAcceptInit
   */
  @Override
  public void onStart(Context ctx) throws Exception {
    Actor socksRef = ctx.createApplicationActor(_socks5Factory.create());

    int socksPort = 19090;
    LOG.debug("SOCKS监听端口：{}", socksPort);
//    _lujnet.createServer().bind("127.0.0.1", socksPort, new BindParam(socksRef));
//    _lujnet.createServer().bind("localhost", 9222, new BindParam(socksRef));

    //TODO: 换直接用netty
    _nettyStarter.inject("localhost", socksPort, socksRef).start();

    int adminPort = 29090;
    LOG.debug("管理页面：127.0.0.1:{}/index", adminPort);
    startAdmin(adminPort, socksRef);

    _springCtx.close();
  }

  private void startAdmin(int port, Actor socksRef) {
    List<HttpHandleCollector.Kit> result = _handleCollector.collect();
    Vertx.vertx().deployVerticle(new MainVerticle(port, result, socksRef, _actorTeller));
  }

  private static final Logger LOG = LoggerFactory.getLogger(OnLujclusterStart.class);

  @Autowired
  NetContext _lujnet;

  @Autowired
  Socks5ActorFactory _socks5Factory;

  @Autowired
  NettySocksStarter _nettyStarter;

  @Autowired
  HttpHandleCollector _handleCollector;

  @Autowired
  ActorTeller _actorTeller;

  @Autowired
  GenericApplicationContext _springCtx;
}
